import React, { PureComponent as Component } from 'react';
// import { formatTime } from '../../../../common.js';
// import { Link } from 'react-router-dom';
// import { getEnv } from '../../../reducer/modules/dubboProject';
// import { setBreadcrumb } from '../../../../reducer/modules/user';
import PropTypes from 'prop-types';
import ProjectEnvContent from './ProjectEnvContent';
import { Table, Popconfirm, message, Button, Modal } from 'antd';
import axios from 'axios';
import {getEnv, getProject, addEnv} from "../../../reducer/modules/dubboProject";
import {connect} from "react-redux";
// const Search = Input.Search;
const limit = 20;

@connect(
    state => {
        return {
            curUserRole: state.user.role,
            projectMsg: state.dubboProject.currProject
        };
    },
    {
        addEnv,
        getProject,
        getEnv
    }
)

class ProjectEnvList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            total: null,
            current: 1,
            backups: [],
            isSearch: false,
            visible: false,
            evnconfig:[],
            currentEnvMsg: {},
            currentKey: -1,
            _id: null
        };
    }
    static propTypes = {
        data: PropTypes.array,
        projectId: PropTypes.number,
        onOk: PropTypes.func,
        addEnv: PropTypes.func,
        getProject: PropTypes.func,
        projectMsg: PropTypes.object,
        getEnv: PropTypes.func
    };

    async componentWillMount() {
        // this._isMounted = true;
        await this.props.getProject(this.props.projectId);
        const { evnconfig, _id } = this.props.projectMsg;
        this.initState(evnconfig, _id);
        this.handleClick(0, evnconfig[0]);
    }
    initState(curdata, id) {
        let newValue = {};
        newValue['evnconfig'] = [].concat(curdata);
        newValue['_id'] = id;
        this.setState({
            ...this.state,
            ...newValue
        });
    }

    showAddMemberModal = () => {
        this.addParams();
        this.setState({
            visible: true
        });
    };

    handleCancel = () => {
        this.setState({
            visible: false
        });
    };

    handleOk = () => {
        this.setState({
            visible: true
        });
    };

    handleSubmit = data => {
        const { email, userName, cname, cellphone, rtxno } = data;
        const param = {
            email,
            username: userName,
            cname,
            cellphone,
            rtxno
        };
        axios.post('/api/user/reg', param).then(res => {
                if (res.data.errcode === 0) {
                    this.setState({
                        visible: false
                    });
                    this.getUserList();
                    message.success('成员添加成功');
                } else {
                    message.error(res.data.errmsg);
                }
            },
            err => {
                message.error(err.message);
            });
    };

    handleSubmits = data => {
        const param = data;
        axios.post('/api/user/add', param).then(res => {
                if (res.data.errcode === 0) {
                    this.setState({
                        visible: false
                    });
                    this.getUserList();
                    message.success('批量添加成功');
                } else {
                    message.error(res.data.errmsg);
                }
            },
            err => {
                message.error(err.message);
            });
    };

    componentDidMount() {
        // this.getUserList();
    }

    handleClick = (key, data) => {
        this.setState({
            currentEnvMsg: data,
            currentKey: key
        });
    };
    addParams = (name, data) => {
        let newValue = {};
        data = { cname: '新环境', dubbourl: '' };
        newValue[name] = [].concat(data, this.state[name]);
        this.setState(newValue);
        this.handleClick(0, data);
    };
    // 删除提示信息
    showConfirm(key, name) {
        let assignValue = this.delParams(key, name);
        this.onSave(assignValue);
    }
    // 删除环境变量项
    delParams = (key, name) => {
        let curValue = this.state.evnconfig;
        let newValue = {};
        newValue[name] = curValue.filter((val, index) => {
            return index !== key;
        });
        this.setState(newValue);
        this.handleClick(0, newValue[name][0]);
        newValue['_id'] = this.state._id;
        return newValue;
    };

    handleInputChange = (value, currentKey) => {
        let newValue = [].concat(this.state.evnconfig);
        console.log(currentKey)
        // console.log(this.state.evnconfig)
        console.log(value)
        //
        // newValue[currentKey].cname = value || '新环境';
        // console.log(newValue[currentKey])
        this.setState({ evnconfig: newValue });
    };
    //  提交保存信息
    onSubmit = (value, index) => {
        let assignValue = {};
        let evnconfig = this.state.evnconfig;
        for(let i=0;i<evnconfig.length;i++){
            delete evnconfig[i]._id;
        }
        evnconfig.push(value.evnconfig);
        assignValue['evnconfig'] = evnconfig;
        assignValue['_id'] = this.state._id;
        this.onSave(assignValue);
        this.props.onOk && this.props.onOk(assignValue['evnconfig'], index);
    };

    async onSave(assignValue) {
        await this.props
            .addEnv(assignValue)
            .then(res => {
                if (res.payload.data.errcode === 0) {
                    this.props.getProject(this.props.projectId);
                    this.props.getEnv(this.props.projectId);
                    message.success('添加成功! ');
                    if(this._isMounted) {
                        this.setState({ ...assignValue });
                    }
                }
            })
            .catch(() => {
                message.error('环境设置不成功 ');
            });
    }

    render() {
        let data = this.state.evnconfig;
        const { currentKey } = this.state;
        let columns = [
            {
                title: '环境名称',
                dataIndex: 'cname',
                key: 'cname'
            },
            {
                title: '环境地址',
                dataIndex: 'dubbourl',
                key: 'dubbourl'
            },
            {
                title: '功能',
                key: 'action',
                width: '90px',
                render: (item, record, index) => {
                    return (
                      <span>
                        <Popconfirm
                                title="确认删除此环境?"
                                onConfirm={e => {
                                    e.stopPropagation();
                                    this.showConfirm(index, 'evnconfig');
                                }}
                                okText="确定"
                                cancelText="取消"
                            >
                          <a style={{ display: 'block', textAlign: 'center' }} href="#">
                              删除
                          </a>
                        </Popconfirm>
                      </span>
                    );
                }
            }
        ];

        const pageConfig = {
            total: this.state.total,
            pageSize: limit,
            current: this.state.current,
            onChange: this.changePage
        };

        const defaultPageConfig = {
            total: data.length,
            pageSize: limit,
            current: 1
        };

        return (
          <section className="user-table">
            <div className="user-search-wrapper"  style={{ marginBottom:'10px', textAlign:"right" }}>
              <Button type="primary" onClick={this.showAddMemberModal}>
                    添加
              </Button>
            </div>
            <Table
                    rowKey={record => record._id}
                    bordered={true}
                    columns={columns}
                    pagination={this.state.isSearch ? defaultPageConfig : pageConfig}
                    dataSource={data}
                />
            <div className="g-row">
              <div className="m-panel">
                {this.state.visible ? (
                  <Modal
                    title="添加环境"
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                    footer={null}
                   >
                    <ProjectEnvContent
                          onCancel={this.handleCancel}
                          projectMsg={this.state.currentEnvMsg}
                          onSubmit={e => this.onSubmit(e, currentKey)}
                          handleEnvInput={e => this.handleInputChange(e,currentKey)}
                      />
                  </Modal>
                        ) : (
                            ''
                        )}
              </div>
            </div>
          </section>
        );
    }
}

export default ProjectEnvList;
